<template>
  <el-dialog
    v-el-drag-dialog
    :title="type === 'edit' ? '编辑调拨计划' : '新增调拨计划'"
    :visible.sync="visible"
    width="1100px"
    @closed="reset"
  >
    <el-form
      ref="dataForm"
      :inline="true"
      label-width="120px"
      :model="temp"
      :rules="rules"
    >
      <el-form-item label="计划调拨日期" prop="executeDate">
        <el-date-picker
          v-model="temp.executeDate"
          type="date"
          alue-format="yyyy-MM-dd"
          placeholder="选择日期"
          :disabled="type === 'edit'"
          style="width: 190px;"
        />
      </el-form-item>
      <el-form-item label="起点站:" prop="startOrgId">
        <el-tree-select
          ref="treeSelect"
          v-model="temp.startOrgId"
          :disabled="type === 'edit'"
          :clearable="true"
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择'
          }"
          :tree-params=" {
            filterable:true,
            'expand-on-click-node': false,
            'highlight-current': true,
            'filterable': true,
            props:{
              value:'orgId',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData
          }"
          @search-clear="searchClear"
          @node-click="selectStartTreeChange"
        />
      </el-form-item>
      <el-form-item label="终点站:" prop="endOrgId">
        <el-tree-select
          ref="treeSelect"
          v-model="temp.endOrgId"
          :disabled="type === 'edit'"
          :clearable="true"
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择'
          }"
          :tree-params=" {
            filterable:true,
            'expand-on-click-node': false,
            'highlight-current': true,
            'filterable': true,
            props:{
              value:'orgId',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData
          }"
          @search-clear="searchClear"
          @node-click="selectEndTreeChange"
        />
      </el-form-item>
      <el-form-item label="调拨车辆" prop="truckCode">
        <el-select v-model="temp.truckCode" :disabled="type === 'edit'" placeholder="请选择" clearable filterable>
          <el-option
            v-for="item in truckList"
            :key="item.truckCode"
            :label="item.truckCode"
            :value="item.truckCode"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="司机" prop="driverId">
        <el-select v-model="temp.driverId" :disabled="type === 'edit'" placeholder="请选择" clearable filterable @change="driverChange">
          <el-option
            v-for="item in driverList"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="押运员">
        <el-select v-model="temp.escortId" :disabled="type === 'edit'" placeholder="请选择" clearable @change="escortChange">
          <el-option
            v-for="item in escortList"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="备注">
        <el-input
          v-model="temp.remarks"
          :disabled="type === 'edit'"
          type="textarea"
          :rows="2"
          placeholder="请输入"
          clearable
          maxlength="200"
          show-word-limit
          style="width: 840px;"
        />
      </el-form-item>
    </el-form>
    <div>
      <h3 class="inline">调拨单列表</h3>
      <el-button type="primary" class="inline add-btn" @click="addAllot">添加调拨单</el-button>
    </div>
    <lb-table
      ref="lbTable"
      border
      :column="tableData.column"
      :data="tableData.data"
    />
    <div class="sum">当前合计{{ sumNum }}瓶</div>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="save">保存</el-button>
      <el-button @click="visible = false">关闭</el-button>
    </div>
    <allot-plan ref="allotPlan" />
  </el-dialog>
</template>

<script>
  import { stockTransPlanSave, stockTransPlanDetail } from '@/api'
  import { mapGetters } from 'vuex'
  import allotPlan from '../components/allotDialog.vue'
  import { parseTime } from '@/utils'
  export default {
    name: 'allot',
    components: { allotPlan },
    props: {
      treeData: {
        type: Array,
        required: true
      },
      truckList: {
        type: Array,
        required: true
      },
      driverList: {
        type: Array,
        required: true
      },
      escortList: {
        type: Array,
        required: true
      }
    },
    data() {
      return {
        visible: false,
        type: '',
        temp: {
          executeDate: new Date(),
          startOrgId: '',
          endOrgId: '',
          truckCode: '',
          driverId: '',
          escortId: '',
          remarks: ''
        },
        rules: {
          startOrgId: [{ required: true, message: '请选择起点站', trigger: 'change' }],
          endOrgId: [{ required: true, message: '请选择终点站', trigger: 'change' }],
          truckCode: [{ required: true, message: '请选择调拨车辆', trigger: 'change' }],
          driverId: [{ required: true, message: '请选择司机', trigger: 'change' }]
        },
        // 右侧列表
        tableData: {
          column: [
            {
              type: 'index',
              label: '序号',
              width: 60
            },
            {
              prop: 'stockTransCode',
              label: '调拨单号',
              width: 100
            },
            {
              prop: 'outStoreName',
              label: '调出仓库',
              width: 120
            },
            {
              prop: 'inStoreName',
              label: '调入仓库',
              width: 120
            },
            {
              prop: 'bottleNum',
              label: '申请数量'
            },
            {
              prop: 'expectDt',
              label: '期望日期',
              width: 160,
              render: (h, { row }) => (
                <span>
                  {row.expectDt && parseTime(row.expectDt, '{y}-{m}-{d}')}
                </span>
              )
            },
            {
              prop: 'remark',
              label: '备注'
            },
            {
              label: '操作',
              width: '90px',
              fixed: 'right',
              render: (h, { row, $index }) => {
                return (
                  ((this.type === 'edit' && row.transStatus === 2) || this.type === 'add') &&
                      <el-link
                        type='primary'
                        underline={false}
                        size='mini'
                        onClick={() => this.handleDel($index)}
                      >
                        删除
                      </el-link>
                )
              }
            }
          ],
          data: [],
          defaultData: []
        },
        sumNum: 0
      }
    },
    computed: {
      ...mapGetters([
        'userInfo', 'corpSettingData'
      ])
    },
    methods: {
      open(type, row) {
        return new Promise((resolve) => {
          this.resolve = resolve
          this.visible = true
          this.type = type
          if (type === 'edit') {
            this.getDetail(row.id)
          }
        })
      },
      async getDetail(id) {
        const res = await stockTransPlanDetail({ id: id })
        console.log(res.data)
        this.temp = { ...res.data }
        this.temp.executeDate = this.temp.executeDate ? parseTime(this.temp.executeDate, '{y}-{m}-{d}') : ''
        this.tableData.data = res.data.billList
        this.sumNum = 0
        if (this.tableData.data.length > 0) {
          this.tableData.data.forEach((item) => {
            this.sumNum += parseInt(item.bottleNum)
          })
        }
      },
      searchClear() {
        if (this.$refs.treeSelect) this.$refs.treeSelect.keywords = ''
      },
      // 选择起点站
      selectStartTreeChange(value) {
        this.temp.startOrgSNNo = value.orgSNNo
        this.temp.startOrgName = value.orgName
      },
      // 选择终点站
      selectEndTreeChange(value) {
        this.temp.endOrgSNNo = value.orgSNNo
        this.temp.endOrgName = value.orgName
      },
      // 押运员
      escortChange(val) {
        const arr = this.driverList.filter((l) => l.userId === val)
        this.$set(this.temp, 'escortName', arr[0].userName)
        this.$set(this.temp, 'escortId', arr[0].userId)
      },
      // 处理司机
      driverChange(val) {
        const arr = this.driverList.filter((l) => l.userId === val)
        this.$set(this.temp, 'driverName', arr[0].userName)
        this.$set(this.temp, 'driverId', arr[0].userId)
      },
      // 添加调拨单
      async addAllot() {
        if (this.temp.truckCode && this.temp.driverId) {
          const res = await this.$refs.allotPlan.open(this.temp)
          console.log(res)
          this.tableData.data = this.tableData.data.concat(res)
          this.sumNum = 0
          this.tableData.data.forEach((item) => {
            this.sumNum += parseInt(item.bottleNum)
          })
        } else {
          this.$message.warning('请先选择调拨车辆和司机')
        }
      },
      // 删除调拨单
      handleDel(index) {
        this.tableData.data.splice(index, 1)
        this.sumNum = 0
        this.tableData.data.forEach((item) => {
          this.sumNum += parseInt(item.bottleNum)
        })
      },
      save() {
        this.$refs.dataForm.validate(async(valid) => {
          if (valid) {
            if (this.temp.endOrgId === this.temp.startOrgId) {
              this.$message.warning('起点站和终点站不能相同')
              return
            }
            if (!this.sumNum) {
              this.$message.warning('调拨计划的调拨数量合计不能为0')
              return
            }
            console.log('save')
            let billIdList = []
            if (this.tableData.data.length > 0) {
              billIdList = this.tableData.data.map((item) => item.id)
            }
            const params = {
              bottleNum: this.sumNum,
              startOrgId: this.temp.startOrgId,
              startOrgSNNo: this.temp.startOrgSNNo,
              startOrgName: this.temp.startOrgName,
              endOrgId: this.temp.endOrgId,
              endOrgSNNo: this.temp.endOrgSNNo,
              endOrgName: this.temp.endOrgName,
              truckCode: this.temp.truckCode,
              driverId: this.temp.driverId,
              driverName: this.temp.driverName,
              escortId: this.temp.escortId,
              escortName: this.temp.escortName,
              remarks: this.temp.remarks,
              executeDate: this.temp.executeDate,
              billIdList: billIdList
            }
            console.log(params)
            if (this.type === 'edit') {
              params.id = this.temp.id
            }
            stockTransPlanSave(params).then((res) => {
              if (res.data) {
                this.$message.success('保存成功')
                this.visible = false
                this.resolve(true)
              }
            })
          } else {
            return false
          }
        })
      },
      reset() {
        this.temp.executeDate = new Date()
        this.temp.startOrgId = ''
        this.temp.endOrgId = ''
        this.temp.truckCode = ''
        this.temp.driverId = ''
        this.temp.escortId = ''
        this.temp.remarks = ''
        this.tableData.data = []
        this.sumNum = 0
        this.$nextTick(() => {
          this.$refs.dataForm.clearValidate()
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
.inline {
  display: inline-block;
}
.add-btn {
  margin-left: 10px;
}
.sum {
  margin-top: 10px;
  color: #F56C6C;
}
</style>
